package com.fan.configService.geetest;


import com.fan.configService.config.Constant;
import com.fan.configService.exception.QhException;
import com.fan.configService.exception.QhUserErrors;
import com.fan.configService.service.redis.RedisOperator;
import com.fan.configService.vo.GeetestVo;
import com.fan.configService.vo.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "Geetest验证码")
@RestController
@RequestMapping("config")
public class GeetestController {
    @Autowired
    Constant constant;
    @Autowired
    RedisOperator redisOperator;


    @ApiOperation(value = "初始化图片验证码")
    @PostMapping("geetest")
    public ResponseResult getGeetest(@RequestBody GeetestVo geetestVo) {
        ResponseResult responseResult = new ResponseResult();
        GeetestLib gtSdk = new GeetestLib(GeetestConfig.getGeetest_id(), GeetestConfig.getGeetest_key(), GeetestConfig.isnewfailback());
        String resStr = "{}";
        //自定义参数,可选择添加
        HashMap<String, String> param = new HashMap<String, String>();
        param.put("user_id", geetestVo.getSessionId()); //网站用户id
        param.put("client_type", "web"); //web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
        param.put("ip_address", "127.0.0.1"); //传输用户请求验证时所携带的IP

        //进行验证预处理
        int gtServerStatus = gtSdk.preProcess(param);

        //将服务器状态设置到session中
        redisOperator.set(gtSdk.gtServerStatusSessionKey.concat("_").concat(geetestVo.getSessionId()), String.valueOf(gtServerStatus), 3600l);
        System.out.println("sessionid:" + geetestVo.getSessionId());
        resStr = gtSdk.getResponseStr();
        responseResult.setData(resStr);
        return responseResult;
    }


    @ApiOperation(value = "验证图片验证码")
    @PostMapping("verifyLogin")
    public ResponseResult verifyLogin(@RequestBody GeetestVo geetestVo) {
        System.out.println("sessionid1:" + geetestVo.getSessionId());
        ResponseResult responseResult = new ResponseResult();
        GeetestLib gtSdk = new GeetestLib(GeetestConfig.getGeetest_id(), GeetestConfig.getGeetest_key(), GeetestConfig.isnewfailback());
        String attribute = redisOperator.get(gtSdk.gtServerStatusSessionKey.concat("_").concat(geetestVo.getSessionId()));
        if (StringUtils.isBlank(attribute)) {
            throw new QhException(QhUserErrors.TOKEN_VERIFY_EXPIRE);
        }
        int gt_server_status_code = Integer.parseInt(attribute);
        //自定义参数,可选择添加
        HashMap<String, String> param = new HashMap<String, String>();
        param.put("user_id", geetestVo.getSessionId()); //网站用户id
        param.put("client_type", "web"); //web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
        param.put("ip_address", "127.0.0.1"); //传输用户请求验证时所携带的IP
        int gtResult = 0;
        if (gt_server_status_code == 1) {
            //gt-server正常，向gt-server进行二次验证
            gtResult = gtSdk.enhencedValidateRequest(geetestVo.getChallenge(), geetestVo.getValidate(), geetestVo.getSeccode(), param);
            System.out.println(gtResult);
        } else {
            // gt-server非正常情况下，进行failback模式验证
            System.out.println("failback:use your own server captcha validate");
            gtResult = gtSdk.failbackValidateRequest(geetestVo.getChallenge(), geetestVo.getValidate(), geetestVo.getSeccode());
            System.out.println(gtResult);
        }
        Map<String, String> map = new HashMap<>();
        if (gtResult == 1) {
            redisOperator.set(constant.getGeetestLib().concat("_").concat(geetestVo.getSessionId()), "1", 60);
            map.put("status", "success");
            map.put("version", gtSdk.getVersionInfo());
        } else {
            // 验证失败
            map.put("status", "fail");
            map.put("version", gtSdk.getVersionInfo());
        }
        responseResult.setData(map);
        return responseResult;
    }

}
